/**
 * 
 */
package cre.gutwo.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.QuoteMode;
import org.apache.commons.io.IOUtils;

import cre.gutwo.domain.DataModel;

/**
 * @author Cre.Gu
 *
 */
public class CsvUtils {

	// CSV文件分隔符
	public static final String NEW_LINE_SEPARATOR = "\n";
	// public static final String ENCODING = "GBK";
	public static final String ENCODING = "UTF-8";
	public static final byte[] UTF8_BOM = { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF };

	public static void writeCsvFile(List<DataModel> datas, String filePath) {
		FrameUtil.println("准备生成csv文件。");
		OutputStreamWriter fileWriter = null;
		CSVPrinter csvFilePrinter = null;
		// 创建 CSVFormat
		CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR)
				.withQuoteMode(QuoteMode.ALL);
		OutputStream output = null;
		try {
			File destF = new File(filePath);
			File dir = destF.getParentFile();
			if (!dir.exists())
				dir.mkdirs();

			output = new FileOutputStream(destF);
			output.write(UTF8_BOM);
			// 初始化FileWriter
			fileWriter = new OutputStreamWriter(output, ENCODING);

			// fileWriter.write(new String(UTF8_BOM));
			// 初始化 CSVPrinter
			csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
			// 创建CSV文件头
			// csvFilePrinter.printRecord(FILE_HEADER);
			for (DataModel dataModel : datas) {
				Set<String> keys = dataModel.keySet();
				csvFilePrinter.printRecord(keys);
				break;
			}

			for (DataModel dataModel : datas) {
				List<String> dataRecord = new ArrayList<String>();

				for (Entry<String, String> entry : dataModel.entrySet()) {
					dataRecord.add(entry.getValue());
				}
				csvFilePrinter.printRecord(dataRecord);
			}

			// 遍历List写入CSV
			FrameUtil.println("CSV文件创建成功！");

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				fileWriter.flush();
				fileWriter.close();
				csvFilePrinter.close();IOUtils.closeQuietly(output);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) throws IOException {
		System.out.println("\u5916\u7F51\u7533\u62A5\u7684\u6750\u6599\u4E0B\u8F7D\u5B58\u653E\u8DEF\u5F84");

		System.out.println(new String(UTF8_BOM));

		OutputStream o = new FileOutputStream("E:\\test.csv");

		o.write(UTF8_BOM);
		o.flush();
	}
}
